package org.learn;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: qingle
 * @Date: 2024/9/8-23:50
 * @Description:
 * @version: 1.0
 */
public class PoolTest01 {

	public static void main(String[] args) {

		// 拒绝策略
		ThreadPoolExecutor.CallerRunsPolicy handler = new ThreadPoolExecutor.CallerRunsPolicy();

		// 创建阻塞队列
		BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(20); // 队列大小为20


		// 创建线程池对象
		ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 5, 0, TimeUnit.SECONDS,
			workQueue,
			handler
//			runnable -> {
//				Thread thread = new Thread(runnable, "自定义线程池线程");
//				thread.setName("我自定义的线程池");
//				return thread;
//			}
		);

		// 创建任务
		Runnable r = () -> {
			System.out.println("线程池中的线程：" + Thread.currentThread().getName());
		};

		// 提交任务
//		threadPoolExecutor.execute(r);

		for (int i = 0; i < 7; i++) {
			threadPoolExecutor.execute(r);
		}

		// 关闭线程池
		threadPoolExecutor.shutdown();
		try {
			if (!threadPoolExecutor.awaitTermination(1, TimeUnit.MINUTES)) {
				threadPoolExecutor.shutdownNow(); // 如果超时未完成，则强制关闭
			}
		} catch (InterruptedException e) {
			threadPoolExecutor.shutdownNow(); // 中断时强制关闭
		}
	}
}
